package org.ihelpuoo.weboo.upload.action;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.ihelpuoo.db.ConnectionProxy;
import org.ihelpuoo.filepool.FilePool;
import org.ihelpuoo.lang.ExceptionUtils;
import org.ihelpuoo.lang.InitializeException;
import org.ihelpuoo.lang.LoaderException;
import org.ihelpuoo.lang.NutException;
import org.ihelpuoo.lang.StringUtils;
import org.ihelpuoo.orm.POJO;
import org.ihelpuoo.orm.filter.CharFieldFilter;
import org.ihelpuoo.orm.filter.FieldFilter;
import org.ihelpuoo.parser.segment.CharSegment;
import org.ihelpuoo.parser.segment.Segment;
import org.ihelpuoo.util.Properties;
import org.ihelpuoo.weboo.action.http.Action;
import org.ihelpuoo.weboo.module.ActionConfig;
import org.ihelpuoo.weboo.module.ActionContext;
import org.ihelpuoo.weboo.module.ModuleContext;
import org.ihelpuoo.weboo.upload.DeleteFileBeanFilter;
import org.ihelpuoo.weboo.upload.FileBean;
import org.ihelpuoo.weboo.upload.Upload;

public class DeleteFileAction implements Action
{
	private static Logger	log	= Logger.getLogger(DeleteFileAction.class);

	private FilePool		filePool;
	private FilePool		indexPool;

	private synchronized void initIndexPool(ModuleContext context, ActionConfig config,
			HttpServletRequest request) throws InitializeException, LoaderException, NutException
	{
		if (null == indexPool)
		{
			String name = config.getPropertyValue(context.getConfig().getStringTrimed(
					"INDEX_POOL_NAME"));
			Properties p = context.nut().getConfig(name);
			Segment seg = new CharSegment(p.getStringTrimed("home"));
			seg.set("appRoot",request.getSession().getServletContext().getRealPath("/"));
			p.setProperty("home",seg.toString());
			indexPool = (FilePool)context.nut().getFactory(p);
		}
	}

	private synchronized void initFilePool(ModuleContext context, ActionConfig config,
			HttpServletRequest request) throws InitializeException, LoaderException, NutException
	{
		if (null == filePool)
		{
			String name = config.getPropertyValue(context.getConfig().getStringTrimed(
					"FILE_POOL_NAME"));
			Properties p = context.nut().getConfig(name);
			Segment seg = new CharSegment(p.getStringTrimed("home"));
			seg.set("appRoot",request.getSession().getServletContext().getRealPath("/"));
			p.setProperty("home",seg.toString());
			filePool = (FilePool)context.nut().getFactory(p);
		}
	}

	private void init(ModuleContext context, ActionConfig config, HttpServletRequest request)
			throws NutException, LoaderException
	{
		if (null == filePool)
			initFilePool(context,config,request);
		if (null == indexPool)
			initIndexPool(context,config,request);
	}

	public void execute(ActionContext context)
	{
		String ids = context.params().getString("ids");
		ConnectionProxy conn = null;
		try
		{
			init(context.getModuleContext(),context.getActionConfig(),context.getRequest());
			if (StringUtils.isBlank(ids))
			{
				context.getResponse().setStatus(500);
				context.getResponse().getWriter().write("id is null");
				return;
			}

			DeleteFileBeanFilter filter = new DeleteFileBeanFilter();
			filter.setIds(ids);
			FieldFilter actived = new CharFieldFilter("[id][name][extension]");
			Class beanType = context.properties().getObjectType();
			List files = context.pojo().query(beanType,filter,actived,null,null);
			Iterator it = files.iterator();
			if (log.isDebugEnabled())
				log.debug("It will delete " + files.size() + " beans!");
			while (it.hasNext())
			{
				FileBean f = (FileBean)it.next();
				if (log.isDebugEnabled())
					log.debug("Delete file [" + f.getId() + "] " + f.getName() + "."
							+ f.getExtension());
				boolean re = filePool.deleteFile(f.getId(),f.getExtension());
				if (log.isDebugEnabled())
					log.debug(" > file:" + re);
				re = indexPool.deleteFile(f.getId(),Upload.ICON_IMG_TYPE);
				if (log.isDebugEnabled())
					log.debug(" > index:" + re);
				re = context.pojo().delete(f,context.properties().getDBIOLockedFieldFilter());
				if (log.isDebugEnabled())
					log.debug(" > db:" + re);
			}
			conn.close();
			conn = null;
			Segment seg = context.createPattern(context.properties().getString("return"));
			context.getResponse().getWriter().write(seg.toString());
			context.getResponse().flushBuffer();
		}
		catch (Exception e)
		{
			log.warn(ExceptionUtils.dump(e));
		}
		finally
		{
			POJO.safeCloseConnection(conn,log);
		}
	}

}
